import { onMounted, onBeforeUnmount, ref } from 'vue'
import axios, { AxiosResponse } from 'axios'

export default function useRequest(url: string, method: "POST"|"DELETE"|"PUT"|"GET") {

    // 声明三大响应式数据
    const loading = ref<boolean>(false)
    const data = ref<AxiosResponse<any, any>>()
    const err = ref<Error | null>(null)

    /* 取消请求需要的配置 */
    let requestCompleted = false
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();

    // 组件一挂载就立即发起ajax请求
    onMounted(
        () => {
            loading.value = true

            axios({
                url,
                cancelToken: source.token
            }).then(
                res => {
                    console.log("data=", data)
                    data.value = res.data
                }
            ).catch(
                error => {
                    console.error("error=", error)
                    err.value = error
                }
            ).finally(
                () => {
                    loading.value = false
                    requestCompleted = true
                }
            )
        }
    )

    // 组件卸载时取消未竟请求
    onBeforeUnmount(
        () => {
            if (!requestCompleted) {
                source.cancel('未竟请求已取消');
            }
        }
    )

    // 返回三大响应式数据
    return {
        loading,
        data,
        err
    }

}